<template>
  <el-cascader
    :modelValue="val"
    :options="items"
    :props="{
      value: ui.value || 'value',
      leaf: ui.leaf || 'leaf',
      disabled: ui.propDisabled || 'disabled',
      label: ui.label || 'label',
      expandTrigger: ui.expandTrigger,
      multiple: ui.multiple,
      emitPath: ui.emitPath,
      checkStrictly: ui.checkStrictly,
      lazy: ui.lazy,
      lazyLoad: layzLoad
    }"
    style="width: 100%"
    :separator="ui.separator"
    :show-all-levels="ui.showAllLevels"
    :size="ui.size"
    :placeholder="ui.placeholder"
    :collapse-tags="ui.collapseTags"
    :disabled="ui.disabled"
    :clearable="ui.clearable"
    :filterable="ui.filterable"
    @update:model-value="updateValue"
  />
</template>

<script lang="ts" setup name="lc-sf-cascader">
import { asyncComputed } from "@vueuse/core";
import { CascaderValue, Resolve } from "element-plus";
import Node, {
  CascaderOption
} from "element-plus/es/components/cascader-panel/src/node";
import { computed, inject } from "vue";
import { CascaderUI } from "../interface";
import { SFService } from "../sf.service";
import { NzSafeAny, TItemOption } from "../type";
const props = defineProps<TItemOption<CascaderUI>>();
const sf = inject<SFService>("sf-service");
const val = computed(() => {
  return sf.getVaule(props.keyPath);
});
const ui = props.service.getUI<CascaderUI>();
const items = asyncComputed<NzSafeAny>(async () => {
  if (typeof ui.items === "function") {
    if (ui.items instanceof Promise) {
      return (await ui.items()) || [];
    }
    return ui.items() || [];
  }
  return ui.items;
});
const layzLoad = (node: Node, resolve: Resolve) => {
  const { value } = node;
  if (ui.lazy && ui.lazyload) {
    if (value) {
      const data = ui.lazyload(value);
      if (data instanceof Promise) {
        data
          .then(async r => {
            resolve((r || []) as CascaderOption[]);
          })
          .catch();
      } else {
        resolve(data as CascaderOption[]);
      }
    } else {
      resolve(items.value as NzSafeAny);
    }
  }
};
const updateValue = (val: CascaderValue) => {
  if (ui.change) {
    ui.change(val);
  }
  sf.setVaule(props.keyPath, val);
};
</script>

<style></style>
../types
